/*global _ctxPath*/
import { useBaseInfoWithOut } from '@/store/modules/base-info';
import globalData from '@/plugins/data';
import globalMethods from '@/plugins/methods';

const getFormFieldTypeAttachment = (formData) => {
  if (!formData || !formData.formmains) return null;

  const FORM_FIELD_INPUT_TYPE = '1872888230778916558'; // 表单转文档控件类型
  let attachment = null;
  for (const Item of Object.values(formData.formmains)) {
    for (const item of Object.values(Item)) {
      const { type, attachmentInfo } = item;
      const { attachmentInfos } = attachmentInfo || {};

      if (type === FORM_FIELD_INPUT_TYPE && attachmentInfos && attachmentInfos.length) {
        attachment = attachmentInfos[0];
      }
    }
  }

  return attachment;
};

function fileDiff() {
  const { businessData, baseInfo } = useBaseInfoWithOut();
  const { template, other, summary } = businessData || {};
  const { formAppId, bodyType } = template || {};

  const dialogParams = {
    summaryId: globalData.summaryId, // 协同id
    affairId: globalData.affairId,
    itemName: summary?.showTitle, // 协同名称
    formId: formAppId, // 表单id
    cap4Flag: baseInfo?.zwIframe?.isCap4
  };

  const compareDialog = globalMethods.dialog({
    id: 'comparePageDialog',
    title: $.i18n('intelli.doc.comparison.contentComparison'),
    url: _ctxPath + '/doc/docComparisonFront.do?method=comparisonPage',
    width: 950,
    bodyStyle:'padding:0',
    centered: true,
    height:  window.top.innerHeight * 0.8,
    targetWindow: window,
    transParams: dialogParams,
    cancelText: $.i18n('intelli.doc.comparison.cancelCompare'),
    okText: $.i18n('intelli.doc.comparison.startCompare'),
    onCancel() {
      compareDialog.close();
    },
    onConfirm() {
      compareDialog.getValue();
    }
  });

  const formData = window._getZWIframe()?.csdk?.core?.getFormData();
  const attachment = formAppId ? getFormFieldTypeAttachment(formData) : null;
  window.transParams = {
    data: {
      ...dialogParams,
      moduleTypeName: other?.moduleTypeName,
      bodyType: bodyType || document.getElementById('bodyType').value
    },
    dialog: compareDialog,
    attachment
  };
}

export default function () {
  return new Promise((resolve) => {
    fileDiff.call(this);
    resolve();
  });
}
